export function ellipsis(origintext: string, length: number) {
  let str = origintext;
  var valid_length = 0;
  for (var i = 0; i < origintext.length; i++) {
    // 判断是否是中文字符，如是 则算两个占位符
    if (str.charCodeAt[i] > 127 || str.charCodeAt[i] == 94) {
      valid_length += 2;
      if (valid_length >= length + 2) {
        str = str.substring(0, length) + "...";
        return str;
      }
    } else {
      valid_length++;
      if (valid_length >= length + 2) {
        str = str.substring(0, length) + "...";
        return str;
      }
    }
  }
  if (valid_length < length + 2) {
    return str;
  }
}

export function formatNumber(num: number): string {
  if (num >= 10000) {
    // 大于等于一万的数字，格式化为 X.XX 万
    const result = (num / 10000).toFixed(1); // 保留两位小数
    return `${result}万`;
  } else {
    // 小于一万的数字，直接显示原值
    return `${5}千+`; // 以千为单位
  }
}

export function timeAgo(date):string {
  const now = new Date();  // 当前时间
  const targetDate = new Date(date);  // 目标日期

  const secondsAgo = Math.floor((now - targetDate) / 1000);  // 转化为秒数

  if (secondsAgo < 60) {
      return `${secondsAgo}秒前`;
  }

  const minutesAgo = Math.floor(secondsAgo / 60);
  if (minutesAgo < 60) {
      return `${minutesAgo}分钟前`;
  }

  const hoursAgo = Math.floor(minutesAgo / 60);
  if (hoursAgo < 24) {
      return `${hoursAgo}小时前`;
  }

  const daysAgo = Math.floor(hoursAgo / 24);
  if (daysAgo < 30) {
      return `${daysAgo}天前`;
  }

  const monthsAgo = Math.floor(daysAgo / 30);
  if (monthsAgo < 12) {
      return `${monthsAgo}个月前`;
  }

  const yearsAgo = Math.floor(monthsAgo / 12);
  return `${yearsAgo}年前`;
}
